/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dale2507.gates.configurator.ui;

import dale2507.gates.data.Settings;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import org.bukkit.Bukkit;

/**
 *
 * @author Dale
 */
public class Configurator extends JFrame {
    
    private static boolean live = false;
    
    public static void main(String[] args) {
        new Configurator();
    }
    
    public static boolean isLive() {
        if (live != true) {
            try {
                Class.forName("org.bukkit.Bukkit");
                if (Bukkit.getServer() != null) live = true;
            } catch (ClassNotFoundException ex) {
                live = false;
            }
        }
        return live;
    }
    
    private CreationSettings creation = new CreationSettings();
    private ConnectionSettings connection = new ConnectionSettings();
    
    public Configurator() {
        if (Configurator.isLive()) {
            this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        } else {
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
        
        this.setTitle("Minecraft Gates Configurator");
        this.setLayout(new BorderLayout());
        
        JTabbedPane tabs = new JTabbedPane();
        tabs.add("Gate Creation", creation);
        tabs.add("Connections", connection);
        this.add(tabs);
        
        JButton save = new JButton("Save");
        save.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (Configurator.isLive()) {
                    try {
                        creation.liveSave();
                        connection.liveSave();
                        Settings.getInstance().save();
                        JOptionPane.showMessageDialog(Configurator.this, "Settings saved. The plugin may need restarting for some settings to take effect.");
                    } catch (IOException ex) {
                        Logger.getLogger(Configurator.class.getName()).log(Level.SEVERE, null, ex);
                        JOptionPane.showMessageDialog(Configurator.this, ex, "Error", JOptionPane.ERROR_MESSAGE);
                    }
                } else {
                    // TODO save to file
                }
            }
        });
        this.add(save, BorderLayout.SOUTH);
        this.getRootPane().setDefaultButton(save);
        
        this.setSize(500, 400);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }
    
}
